<template>
  <div class="containers">
    <div id="bpmn-view" ref="abc"></div>
  </div>
  <div style="width: 100%">
    <Table :tableData="tableData" :havePage="false" :columnData="columnData" />
  </div>
</template>

<script>
import bpmn from 'bpmn-js'
import {
current_trace,
flow,
getBlankUserAlias,
getUserAlias,
queryFileStr,
trace,
} from '../utils/api'
import format from '../utils/format'
import Table from './Table.vue'
export default {
  name: 'Modal',
  data() {
    return {
      tableData: [], //表格数据
      bpmnXML: '',
      taskDefinitionKey: '', //当前任务
      activeId: '',
      columnData: [
        { title: '当前环节', prop: 'name' },
        { title: '批注人姓名', prop: 'userName' },
        {
          title: '批注内容',
          prop: 'createTime',
          formatter: (row) => {
            return `<div>${row.comment.map((item) => item.message).join(',')}</div>`
          },
        },
        {
          title: '任务开始时间',
          prop: 'startTime',
          formatter: ({ startTime }) => {
            return startTime ? format(startTime, 'YYYY-MM-DD HH:mm:ss') : '暂无日期'
          },
        },
        {
          title: '批注时间',
          prop: 'endTime',
          formatter: ({ endTime }) => {
            return endTime ? format(endTime, 'YYYY-MM-DD HH:mm:ss') : '暂无日期'
          },
        },
      ], //表头数据
      pageOption: {},
    }
  },
  props: {
    info: {
      type: Object,
      default: () => {
        return undefined
      },
    },
    changeChart: {
      type: Function,
      default: () => {
        return undefined
      },
    },
  },
  inject: ['parent'],
  methods: {
    clear() {
      if (this.viewer) {
        this.viewer.destroy()
      }
    },
    async getTableData() {
      let flowData = this?.parent?.flowData
      if (!flowData && this?.info?.approvalNo) {
        await flow({ processInstanceId: this?.info?.approvalNo }).then((res) => {
          flowData = res.data
        })
        if (!flowData) return
      }
      var res = await trace(flowData?.processInstanceId)
      const { data } = res
      if (res.success) {
        let pname = res?.data?.map((item) => item.assignee).filter((i) => i !== null)
        if (data?.[0]?.assignee === null) {
          const { processIntanceId, taskDefinitionKey } = data?.[0]
          const { code, data: ds } = await getBlankUserAlias({
            processIntanceId,
            taskDefinitionKey,
          })
          if (code === 200 && ds) {
            res.data[0].assignee = ds.users.split(', ')
            pname = pname.concat(ds.users.split(', '))
          }
        }
        const params = pname.map((item) => 'usernameList=' + item)
        const user = await getUserAlias(params)
        res.data = res?.data?.map((val) => {
          // let userName = user?.data
          //   ?.filter((v) => val.assignee?.includes(v.username))
          //   .map((i) => i.cname)
          //   .join(',')
          return Object.assign(
            val,
            val.assignee && {
              userName: val.userName,
            }
          )
        })
      }
      var rst = await queryFileStr(flowData?.processDefinitionId)
      this.tableData = res?.data
      var TaskData1 = await current_trace(flowData?.processInstanceId)
      var TaskData = TaskData1?.data?.[0]
      var taskDefinitionKey = TaskData?.taskDefinitionKey
      this.initBpmn(taskDefinitionKey, rst.data)
      // if (this.$refs.abc.children.length > 1) {
      //   this.$refs.abc.firstElementChild.style.display = 'none'
      // }
    },
    initBpmn(taskDefinitionKey, XMLData) {
      if (this.viewer) {
        this.viewer.detach()
      }
      var viewer = new bpmn({
        container: '#bpmn-view',
      })
      this.viewer = viewer
      viewer.importXML(XMLData.content, (err) => {
        if (err) {
          console.error(err)
        } else {
          // 这里是成功之后的回调, 可以在这里做一系列事情
          // var overlays = viewer.get("overlays"); //获取over视图
          var elementRegistry = viewer.get('elementRegistry')
          // if (taskDefinitionKey) {
          var shape = elementRegistry.get(taskDefinitionKey)
          var arr = []
          this.tableData.map((itme) => {
            arr.push(itme.taskDefinitionKey)
          })
          let canvas = viewer.get('canvas')
          // nodeCodes为需要设置高亮颜色的部分的id的集合（xml文件中<flowNodeRef>****</flowNodeRef>标签里的部分），这个数据也是从接口获取，这里从xml中随便取出几个测试用
          this.setNodeColor(arr, 'nodeSuccess', canvas) //节点走过的颜色
          if (shape) {
            this.setNodeColor([shape], 'nodeSuccessa', canvas) //当前节点的背景颜色
          }
          // }
          this.addEventBusListener(viewer)
        }
      })
    },
    // 设置高亮颜色的class
    setNodeColor(nodeCodes, colorClass, canvas) {
      for (let i = 0; i < nodeCodes.length; i++) {
        canvas.addMarker(nodeCodes[i], colorClass)
      }
    },
    /**
     * @description: 设立监听
     * @param {*} bpmnModeler
     * @return {*}
     */
    addEventBusListener(bpmnModeler) {
      const overlays = bpmnModeler.get('overlays')
      const eventBus = bpmnModeler.get('eventBus') // 需要使用eventBus
      const eventTypes = ['element.hover', 'element.click'] // 需要监听的事件集合
      // const bpmn_htmls = document.getElementsByClassName('highlight-boder')
      // bpmn_htmls.forEach((item) => {
      //   item.addEventListener('mouseenter', () => {
      //     if (this.activeId) {
      //       overlays.remove(this.activeId)
      //     }
      //     let div = document.createElement('div')
      //     div.innerHTML = `<div id='tiplayer' style='position:absolute;z-index:999;top:-50px'>啊啊啊啊</div>`
      //     div.classList.add('bpmn_msg')
      //     item.appendChild(div)
      //   })
      //   item.addEventListener('mouseleave', () => {
      //     if (this.activeId) {
      //       overlays.remove(this.activeId)
      //     }
      //     let classList = document.getElementsByClassName('bpmn_msg')
      //     classList.forEach((i) => {
      //       item.removeChild(i)
      //     })
      //   })
      // })
      eventTypes.forEach((eventType) => {
        eventBus.on(eventType, (e) => {
          if (!e) return
          if (e.element.type == 'bpmn:Process') {
            overlays.remove(this.activeId)
            return
          }
          switch (eventType) {
            case 'element.hover':
              this.elementHover(bpmnModeler, overlays, e)
              break
            case 'element.click':
              break
            default:
              break
          }
        })
      })
    },
    /**
     * @description: 鼠标划过事件
     * @param {*}
     * @return {*}
     */

    elementHover(bpmnModeler, overlays, e) {
      let info = this.tableData.filter(
        (item) => item.name === e.gfx.textContent.replace(/\s*/g, '')
      )
      if (!info.length) return
      if (this.activeId) {
        overlays.remove(this.activeId)
      }
      if (
        e.element.type == 'bpmn:StartEvent' ||
        e.element.type == 'bpmn:SequenceFlow' ||
        e.element.type == 'label' ||
        e.element.type == 'bpmn:EndEvent'
      ) {
        return
      }

      var elementId = overlays.add(e.element.id, {
        position: {
          top: -50,
        },
        html: `<div id='tiplayer'>${info.map((item) => {
          return ` <p>审批人:${item.userName}</p>
                <p>审批时间:${
                  item.startTime ? format(item.startTime, 'YYYY-MM-DD HH:mm:ss') : ''
                }</p>`
        })}</div>`,
      })

      this.activeId = elementId
    },
  },
  components: {
    Table,
  },
  //生命周期 - 创建完成（访问当前this实例）
  //   created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    if (!this.info) {
      this.getTableData()
    }
  },
}
</script>
<style lang="scss">
.bpmn_msg {
  color: red;
}
</style>
<style scoped lang="scss">
/* @import url(); 引入scss类 */
.canvas {
  margin: 10px;
}
::v-deep .nodeSuccess:not(.djs-connection) {
  .djs-visual {
    > :nth-child(1) {
      stroke: green !important;
      stroke-width: 3px !important;
    }
  }
}
::v-deep .nodeSuccessa:not(.djs-connection) {
  .djs-visual {
    > :nth-child(1) {
      fill: green !important;
      fill-opacity: 0.4 !important;
    }
  }
}
.containers {
  background-color: #ffffff;
  width: 100%;
  height: 50vh;
  overflow: auto;
  #bpmn-view {
    width: 100%;
    height: 100%;
    ::v-deep .viewport {
      margin: 0 auto;
    }
    ::v-deep #verify_01 {
      background: red;
    }
    ::v-deep #tiplayer {
      background: green;
      padding: 10px;
      position: absolute;
      z-index: 999;
      left: 111px;
      top: 40px;
      width: auto;
      height: auto;
      & > p {
        color: #fff;
        white-space: nowrap;
      }
      &::after {
        content: '';
        position: absolute;
        left: -20px;
        z-index: 9999;
        top: 40px;
        border: 10px solid;
        border-color: transparent green transparent transparent;
      }
    }

    ::v-deep .bjs-powered-by {
      display: none;
    }
  }
  .bjs-powered-by {
    display: none;
  }
}
</style>
